package org.ddl.core.context;

import java.util.Map;

import org.ddl.core.entity.DataSourceTable;
import org.ddl.core.strategy.DataSourceShardStrategy;
import org.ddl.core.strategy.TableShardStrategy;

/**
 * 上下文内容
 * 
 * <pre>
 * 1.线程变量currentDataSourceTableContext，保存表名、数据源key 
 * 2.分表算法
 * 3.分库算法
 * </pre>
 * 
 * @author yinjianwei
 * @date 2017年9月11日 下午10:00:53
 *
 */
public class ShardContext {
	/**
	 * 分库分表上下文配置
	 */
	private static final ThreadLocal<DataSourceTable> currentDataSourceTableContext = new ThreadLocal<DataSourceTable>();

	/**
	 * 分表算法
	 */
	private Map<String, TableShardStrategy> tableShardStrategies;

	/**
	 * 分库算法
	 */
	private Map<String, DataSourceShardStrategy> dataSourceShardStrategies;

	/**
	 * 设置分库分表上下文配置
	 * 
	 * @param lookup
	 */
	public static void setCurrentDataSourceTableContext(DataSourceTable dataSourceTableContext) {
		currentDataSourceTableContext.set(dataSourceTableContext);
	}

	/**
	 * 获取分库分表上下文配置
	 * 
	 * @return
	 */
	public static DataSourceTable getCurrentDataSourceTableContext() {
		return currentDataSourceTableContext.get();
	}

	/**
	 * 获取数据源key
	 * 
	 * @return
	 */
	public static String getDataSourceKey() {
		DataSourceTable dataSourceTable = currentDataSourceTableContext.get();
		return dataSourceTable.getDataSourceKey();
	}

	/**
	 * 根据类型获取分库策略
	 * 
	 * @param dataSourceShardType
	 * @return
	 */
	public DataSourceShardStrategy getDataSourceShardStrategy(String dataSourceShardType) {
		return dataSourceShardStrategies.get(dataSourceShardType);
	}

	/**
	 * 根据类型获取分表策略
	 * 
	 * @return
	 */
	public TableShardStrategy getTableShardStrategy(String tableShardType) {
		return tableShardStrategies.get(tableShardType);
	}

	public Map<String, TableShardStrategy> getTableShardStrategies() {
		return tableShardStrategies;
	}

	public void setTableShardStrategies(Map<String, TableShardStrategy> tableShardStrategies) {
		this.tableShardStrategies = tableShardStrategies;
	}

	public Map<String, DataSourceShardStrategy> getDataSourceShardStrategies() {
		return dataSourceShardStrategies;
	}

	public void setDataSourceShardStrategies(Map<String, DataSourceShardStrategy> dataSourceShardStrategies) {
		this.dataSourceShardStrategies = dataSourceShardStrategies;
	}

}
